// Copyright 2008 David Mitchell
// Released under the MIT License

using System;
using System.Drawing;
using System.Runtime.InteropServices;

namespace NSDuctTape
{
	public static class NativeColor
	{
		public static Color NativeColorToColor(IntPtr value)
		{
			if (value == IntPtr.Zero)
				return default(Color);

			IntPtr nativeColor = ObjectiveCMethods.SendMessage(value, Selectors.ColorUsingColorSpace,
				ObjectiveCMethods.SendMessage(Classes.ColorSpace, Selectors.GenericRgbColorSpace));
			
			// TODO: Use double if we're in 64-bit mode
			using (HGlobal buffer = new HGlobal(sizeof(Single) * 4))
			{
				ObjectiveCMethods.SendMessage(nativeColor, Selectors.GetComponents, buffer.ToIntPtr());
				float[] array = new float[4];
				Marshal.Copy(buffer.ToIntPtr(), array, 0, 4);
				
				byte red = FloatToByte(array[0]);
				byte green = FloatToByte(array[1]);
				byte blue = FloatToByte(array[2]);
				byte alpha = FloatToByte(array[3]);
				
				return Color.FromArgb(alpha, red, green, blue);
			}
		}
		
		public static IntPtr ColorToNativeColor(Color value)
		{
			return ObjectiveCMethods.SendMessage(Classes.Color, Selectors.ColorWithCalibratedRedGreenBlueAlpha,
				ByteToFloat(value.R), ByteToFloat(value.G), ByteToFloat(value.B), ByteToFloat(value.A));
		}
		
		private static byte FloatToByte(float value)
		{
			if (value < 0.0f)
				return 0;
			
			if (value > 1.0f)
				return 255;
			
			return (byte)(value * 255);
		}
		
		private static float ByteToFloat(byte value)
		{
			return value / 255.0f;
		}
	}
}